package servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class DownloadFile
 */
public class DownloadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadFile() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String filename = request.getParameter("filename");
		String path = request.getParameter("path");
		if(filename==null || filename.trim().equals("") || path==null || path.trim().equals("")) {
			System.out.println("Error, redirect to the error processing page!");
			return;
		}
		
		OutputStream os = response.getOutputStream();
		byte b[] = new byte[1024];
		// the file to download.
//		File fileLoad = new File("C:/Users/xijiang/workspace/BAIGeneratorProject/generated_files/", filename);//the generated file dir
		File fileLoad = new File(path);
		// the dialogbox of download file.
		response.setHeader("Content-disposition", "attachment;filename="+filename);
		// set the MIME type.
//		response.setContentType("application/x-tar");
		// get the file length.
		long fileLength = fileLoad.length();
		String length = String.valueOf(fileLength);
		response.setHeader("Content_Length", length);
		// download the file.
		FileInputStream in = new FileInputStream(fileLoad);
		int n = 0;
		while ((n = in.read(b)) != -1) {
			os.write(b, 0, n);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}
